<?php
	$menu = array('id' => intval($_REQUEST['menus_id']));
	
	if (local_post()) {
		$errors = array();
		
		if (!empty($errors)) errors($errors);
		else {
			$menu['name'] = db_escape_string($_POST['name']);
			$menu['auto_add_pages'] = db_escape_string($_POST['auto_add_pages']);
			
			$menu = db_save($menu, 'menus');
			
			foreach ($_POST['menu_links'] as $menu_links_id => $menu_link) {
				$menu_link['id'] = $menu_links_id;
				$menu_link['menus_id'] = $menu['id'];
				
				//skip new link if not filled out.
				if ($menu_link['id'] == 0 && empty($menu_link['label'])) continue;
				
				if ($menu_link['delete'] == 1 && authorized('menu_links', 'delete', true)) {
					db_query("DELETE FROM menu_links WHERE id = {$menu_link['id']}");
				} else db_save($menu_link, 'menu_links');
			}
			
			if ($_POST['button'] == 'Save and Close') location('/menus/admin/index');
			elseif ($_POST['button'] == 'Save and New') location('/menus/admin/edit');
		}
	}
	
	$menu = db_select($menu['id'], 'menus');
?>

<form action="?menus_id=<?php echo $menu['id']?>" method="post">
	<fieldset>
		<legend>Manu</legend>
		
		<label for="name">
			Name
			<input type="text" name="name" id="name" value="<?php echo $menu['name']?>" />
		</label>
		
		<label for="auto_add_pages">
			<input type="checkbox" name="auto_add_pages" id="auto_add_pages" value="1" <?php if ($menu['auto_add_pages'] == 1) echo 'checked="checked" '; ?>/>
			Auto-add new Pages to this Menu
		</label>
	</fieldset>
	
	<fieldset>
		<legend>Links / Buttons</legend>
	
		<?php
			menu_links_admin($menu['id']);
		?>		
	</fieldset>
	
	<fieldset>
		<legend>Add a New Link</legend>
		
    <label for="menu_link_0_label">
  		Label
  		<input type="text" name="menu_links[0][label]" id="menu_link_0_label" value="" />
  	</label>
  	
  	<label for="menu_link_0_uri">
  		URI
  		<input type="text" name="menu_links[0][uri]" id="menu_link_0_uri" value="" />
  	</label>
  	
  	<label for="menu_link_0_parent_id">
  		Parent
  		<select name="menu_links[0][parent_id]" id="menu_link_0_parent_id">
  			<option value="0"> - MAIN MENU ITEM - </option>
  	<?php
  		menu_links_select_options($menus_id, 0, $menu_link['parent_id']);
  	?>
  		</select>
  	</label>
	</fieldset>
	
	<?php save_buttons(); ?>
</form>